package com.zzmcc.wechat.action;

import com.zzmcc.wechat.Constant;
import com.zzmcc.wechat.WeChat;
import com.zzmcc.wechat.entity.Account;
import com.zzmcc.wechat.service.AccountService;
import com.zzmcc.wechat.service.WechatService;
import com.zzmcc.wechat.util.Tools;
import org.smart4j.framework.ioc.annotation.Inject;
import org.smart4j.framework.mvc.DataContext;
import org.smart4j.framework.mvc.annotation.Action;
import org.smart4j.framework.mvc.annotation.Request;
import org.smart4j.framework.mvc.bean.Params;
import org.smart4j.framework.mvc.bean.Result;
import org.smart4j.framework.util.CastUtil;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by joinwin on 14-6-20.
 */
@Action
public class WechatAction {
    @Inject
    private AccountService accountService;
    @Inject
    private WechatService wechatService;

    @Request.Get("/wechat/{id}")
    public String doGet(long id,Params params){
        //String _token = Constant.TOKEN;
        Account account=accountService.findAccount(id);
        String _token;
        if(account!=null){
             _token = account.getToken();
        }else{
             _token = CastUtil.castString(id);
        }

        String signature = params.getString("signature");// 微信加密签名
        String timestamp = params.getString("timestamp");// 时间戳
        String nonce =params.getString("nonce");// 随机数
        String echostr = params.getString("echostr");//
        // 验证
        String outPut = "error";

        if (Tools.checkSignature(_token, signature, timestamp, nonce)) {
             outPut=echostr;
        }
        return  outPut;

    }

    @Request.Post("/debug/{id}")
    public Result debug(String id,Params params){

        String xmlMsg =params.getString("inMessage");
        String handler = "wechat.message_processing_handler_"+id;
        String outMsg = wechatService.processing(xmlMsg,handler);

        return  new Result(true).data(outMsg);

    }

    @Request.Post("/wechat/{id}")
    public  String doPost(String id,Params params){

        try {
            String handler = "wechat.message_processing_handler_"+id;
            HttpServletRequest request= DataContext.getRequest();
            ServletInputStream in = request.getInputStream();
            String xmlMsg = Tools.inputStream2String(in);
            String outMsg = wechatService.processing(xmlMsg,handler);
            return  outMsg;
        }catch (IOException e){
            return  "";
        }


    }

}
